package app

import (
	"fmt"
	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"jgame-api/config"
	"os"
	"time"
)

// createZap 创建zap.SugaredLogger
func createZap(conf config.LoggerConf) *zap.Logger {
	levelName := conf.Level

	var level = zapcore.DebugLevel
	if err := level.Set(levelName); err != nil {
		fmt.Printf("logger level name [%s] is wrong", levelName)
		os.Exit(0)
	}

	core := zapcore.NewCore(getEncoder(), getLogWriter(conf), level)
	return zap.New(core, zap.AddCaller())
}

func getEncoder() zapcore.Encoder {
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05.000")
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	return zapcore.NewConsoleEncoder(encoderConfig)
}

func getLogWriter(conf config.LoggerConf) zapcore.WriteSyncer {
	hook, err := rotatelogs.New(
		conf.Filename+"%Y%m%d.log",
		rotatelogs.WithLinkName(conf.Filename),
		rotatelogs.WithMaxAge(time.Duration(conf.MaxAge*24)*time.Hour),
		rotatelogs.WithRotationCount(uint(conf.MaxBackups)),
	)
	if err != nil {
		fmt.Printf("logger rotate init fail, err:%v", err)
		os.Exit(0)
	}

	if conf.Writer == "both" {
		return zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout), zapcore.AddSync(hook))
	}

	if conf.Writer == "file" {
		return zapcore.AddSync(hook)
	}
	// 默认输出控制台
	return zapcore.AddSync(os.Stdout)
}
